from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File, Form, BackgroundTasks, Query
from fastapi.responses import StreamingResponse, FileResponse
from sqlalchemy.orm import Session
from pydantic import BaseModel
from typing import List, Optional, Union
import os
import uuid
import re
import json
from datetime import datetime

from database import get_db, User, ChatSession, ChatMessage, get_beijing_time
from auth import get_current_user
from ai_models import ai_agent
from config import settings
from redis_service import redis_service

router = APIRouter(prefix="/chat", tags=["聊天"])


class UploadConfigResponse(BaseModel):
    """文件上传配置响应模型"""
    max_file_size: int
    allowed_extensions: List[str]


class ChatSessionCreate(BaseModel):
    title: Optional[str] = None


class ChatSessionInfo(BaseModel):
    id: str
    title: str
    pinned: bool = False
    created_at: datetime
    updated_at: datetime


class ChatMessageInfo(BaseModel):
    id: str  # 统一使用字符串GUID
    session_id: str  # 统一使用字符串GUID
    content: str
    message_type: str
    is_user: bool
    created_at: datetime
    file_path: Optional[str] = None
    is_streaming: Optional[bool] = False
    is_final: Optional[bool] = True


async def generate_session_title_with_ai(content: str) -> str:
    """使用AI大模型生成智能会话标题"""
    try:
        from ai_models import ai_agent

        # 构建AI提示词
        prompt = f"""请根据以下用户消息内容，生成一个简洁、有意义的会话标题。

要求：
1. 标题长度控制在10-15个字符以内
2. 标题要能准确概括消息的核心内容
3. 使用中文，语言简洁明了
4. 避免使用"关于"、"讨论"等泛化词语
5. 如果是问题，提取核心问题；如果是陈述，提取核心主题

用户消息：{content}

请直接返回标题内容，不要添加任何解释或说明。"""

        # 调用AI模型生成标题
        messages = [{"role": "user", "content": prompt}]
        ai_response = await ai_agent.openai_model.chat(messages)

        # 清理AI返回的内容，确保是纯标题
        title = ai_response.strip()

        # 如果AI返回的内容过长，进行截取
        if len(title) > 20:
            title = title[:20] + "..."

        # 如果AI返回空或异常，使用备用方案
        if not title or len(title) < 2:
            return generate_fallback_title(content)

        return title

    except Exception as e:
        print(f"AI生成会话标题失败: {e}")
        # AI服务不可用时使用备用方案
        return generate_fallback_title(content)


def generate_fallback_title(content: str) -> str:
    """备用方案：基于消息内容生成精简的会话标题"""
    # 清理内容，移除特殊字符和多余空格
    cleaned_content = re.sub(r'[^\w\u4e00-\u9fff\s]', ' ', content)
    cleaned_content = re.sub(r'\s+', ' ', cleaned_content).strip()

    # 如果内容太短，直接返回
    if len(cleaned_content) <= 15:
        return cleaned_content

    # 提取前几个关键词作为标题
    words = cleaned_content.split()

    # 中文处理：按字符分割
    if any('\u4e00' <= char <= '\u9fff' for char in cleaned_content):
        # 中文内容，取前8-12个字符
        if len(cleaned_content) <= 12:
            return cleaned_content
        else:
            return cleaned_content[:12] + "..."
    else:
        # 英文内容，取前3-5个单词
        if len(words) <= 5:
            return ' '.join(words)
        else:
            return ' '.join(words[:5]) + "..."


@router.get("/upload-config", response_model=UploadConfigResponse)
async def get_upload_config():
    """获取文件上传配置"""
    return UploadConfigResponse(
        max_file_size=settings.max_file_size,
        allowed_extensions=settings.allowed_extensions
    )


@router.get("/sessions", response_model=List[ChatSessionInfo])
async def get_chat_sessions(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取用户的聊天会话列表"""
    sessions = db.query(ChatSession).filter(
        ChatSession.user_id == current_user.id
    ).order_by(ChatSession.pinned.desc(), ChatSession.updated_at.desc()).all()

    return sessions


@router.post("/sessions", response_model=ChatSessionInfo)
async def create_chat_session(
    session_data: ChatSessionCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建新的聊天会话"""
    # 如果没有传递标题，使用默认值"新会话"
    title = session_data.title if session_data.title else "新会话"

    new_session = ChatSession(
        user_id=current_user.id,
        title=title
    )

    db.add(new_session)
    db.commit()
    db.refresh(new_session)

    return new_session


@router.get("/sessions/{session_id}/messages", response_model=List[ChatMessageInfo])
async def get_chat_messages(
    session_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取指定会话的聊天消息（数据库中的消息）"""
    # 验证会话属于当前用户
    session = db.query(ChatSession).filter(
        ChatSession.id == session_id,
        ChatSession.user_id == current_user.id
    ).first()

    if not session:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="会话不存在"
        )

    # 查询会话的所有消息，按创建时间排序
    messages = db.query(ChatMessage).filter(
        ChatMessage.session_id == session_id
    ).order_by(ChatMessage.created_at.asc()).all()

    # 创建消息列表
    all_messages = []

    # 添加数据库消息
    for msg in messages:
        all_messages.append({
            "id": msg.id,
            "session_id": msg.session_id,
            "content": msg.content,
            "message_type": msg.message_type,
            "is_user": msg.is_user,
            "file_path": msg.file_path,
            "created_at": msg.created_at,
            "is_streaming": getattr(msg, 'is_streaming', False),
            "is_final": getattr(msg, 'is_final', True)
        })

    # 转换为响应模型
    return [
        ChatMessageInfo(
            id=msg["id"],
            session_id=msg["session_id"],
            content=msg["content"],
            message_type=msg["message_type"],
            is_user=msg["is_user"],
            file_path=msg["file_path"],
            created_at=msg["created_at"],
            is_streaming=msg["is_streaming"],
            is_final=msg["is_final"]
        )
        for msg in all_messages
    ]


class ChatSessionUpdate(BaseModel):
    """会话更新模型"""
    title: Optional[str] = None
    pinned: Optional[bool] = None


@router.patch("/sessions/{session_id}")
async def update_chat_session(
    session_id: str,
    session_data: ChatSessionUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新聊天会话"""
    # 验证会话属于当前用户
    session = db.query(ChatSession).filter(
        ChatSession.id == session_id,
        ChatSession.user_id == current_user.id
    ).first()

    if not session:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="会话不存在"
        )

    # 更新会话属性
    if session_data.title is not None:
        session.title = session_data.title

    if session_data.pinned is not None:
        session.pinned = session_data.pinned

    # 只有在实际修改内容时才更新时间戳
    if session_data.title is not None or session_data.pinned is not None:
        session.updated_at = get_beijing_time()

    db.commit()

    return {"message": "会话更新成功"}


@router.patch("/sessions/{session_id}/pin")
async def pin_chat_session(
    session_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """置顶聊天会话"""
    # 验证会话属于当前用户
    session = db.query(ChatSession).filter(
        ChatSession.id == session_id,
        ChatSession.user_id == current_user.id
    ).first()

    if not session:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="会话不存在"
        )

    # 更新置顶状态（不更新updated_at，避免日期变化）
    session.pinned = True

    db.commit()

    return {"message": "会话已置顶"}


@router.patch("/sessions/{session_id}/unpin")
async def unpin_chat_session(
    session_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """取消置顶聊天会话"""
    # 验证会话属于当前用户
    session = db.query(ChatSession).filter(
        ChatSession.id == session_id,
        ChatSession.user_id == current_user.id
    ).first()

    if not session:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="会话不存在"
        )

    # 更新置顶状态（不更新updated_at，避免日期变化）
    session.pinned = False

    db.commit()

    return {"message": "会话已取消置顶"}


@router.delete("/sessions/{session_id}")
async def delete_chat_session(
    session_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除聊天会话"""
    # 验证会话属于当前用户
    session = db.query(ChatSession).filter(
        ChatSession.id == session_id,
        ChatSession.user_id == current_user.id
    ).first()

    if not session:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="会话不存在"
        )

    # 删除会话相关的所有消息
    db.query(ChatMessage).filter(ChatMessage.session_id == session_id).delete()

    # 删除会话
    db.delete(session)
    db.commit()

    return {"message": "会话删除成功"}


@router.post("/upload-file")
async def upload_file(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """上传文件"""
    from config import settings

    # 检查文件大小
    file_content = await file.read()
    if len(file_content) > settings.max_file_size:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"文件大小超过限制（最大{settings.max_file_size}字节）"
        )

    # 检查文件类型
    file_extension = file.filename.split('.')[-1].lower()
    if file_extension not in settings.allowed_extensions:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"不支持的文件类型，支持的类型：{', '.join(settings.allowed_extensions)}"
        )

    # 判断文件类型：图片还是普通文件
    is_image = file_extension in ['jpg', 'jpeg', 'png', 'gif']
    
    # 创建不同的上传目录
    if is_image:
        upload_dir = "uploads/images"
    else:
        upload_dir = "uploads/files"
    
    if not os.path.exists(upload_dir):
        os.makedirs(upload_dir)

    # 生成唯一文件名
    unique_filename = f"{uuid.uuid4()}_{file.filename}"
    file_path = os.path.join(upload_dir, unique_filename)

    # 保存文件
    with open(file_path, "wb") as f:
        f.write(file_content)

    # 保存文件记录到数据库
    from database import UploadedFile
    uploaded_file = UploadedFile(
        user_id=current_user.id,
        filename=file.filename,
        file_path=file_path,
        file_size=len(file_content),
        file_type=file_extension
    )

    db.add(uploaded_file)
    db.commit()
    db.refresh(uploaded_file)

    return {
        "file_id": uploaded_file.id,
        "filename": file.filename,
        "file_path": file_path,
        "is_image": is_image,
        "message": "文件上传成功"
    }


@router.get("/download-file/{file_id}")
async def download_file(
    file_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """下载文件"""
    from database import UploadedFile
    
    # 查询文件记录
    uploaded_file = db.query(UploadedFile).filter(
        UploadedFile.id == file_id,
        UploadedFile.user_id == current_user.id
    ).first()
    
    if not uploaded_file:
        raise HTTPException(status_code=404, detail="文件不存在或无权访问")
    
    # 检查文件是否存在
    if not os.path.exists(uploaded_file.file_path):
        raise HTTPException(status_code=404, detail="文件不存在")
    
    # 返回文件下载响应
    return FileResponse(
        path=uploaded_file.file_path,
        filename=uploaded_file.filename,
        media_type='application/octet-stream'
    )


class StreamResponse(BaseModel):
    """流式响应模型"""
    content: str
    is_final: bool = False


@router.post("/sessions/{session_id}/send-message-stream", response_class=StreamingResponse)
async def send_chat_message_stream(
    session_id: str,
    message: str = Form(...),
    message_type: str = Form("text"),
    file: UploadFile = File(None),
    enable_search: bool = Form(True),  # 默认开启搜索
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """发送聊天消息（流式响应） - 支持多会话并发和流式消息恢复功能，支持联网搜索"""
    message_id = None

    # 验证会话存在且属于当前用户
    session = db.query(ChatSession).filter(
        ChatSession.id == session_id,
        ChatSession.user_id == current_user.id
    ).first()
    if not session:
        raise HTTPException(status_code=404, detail="会话不存在")

    # 检查消息数量限制
    message_count = db.query(ChatMessage).filter(
        ChatMessage.session_id == session_id).count()
    if message_count >= 1000:  # 限制每个会话最多1000条消息
        raise HTTPException(status_code=400, detail="会话消息数量已达上限")

    # 处理文件上传
    file_data = None
    file_path = None
    if file:
        # 验证文件大小
        file.file.seek(0, 2)  # 移动到文件末尾
        file_size = file.file.tell()
        file.file.seek(0)  # 重置文件指针

        if file_size > 10 * 1024 * 1024:  # 10MB限制
            raise HTTPException(status_code=400, detail="文件大小超过10MB限制")

        # 读取文件数据
        file_data = await file.read()

        # 判断文件类型：图片还是普通文件
        file_extension = file.filename.split('.')[-1].lower()
        is_image = file_extension in ['jpg', 'jpeg', 'png', 'gif']
        
        # 创建不同的上传目录
        if is_image:
            upload_dir = "uploads/images"
        else:
            upload_dir = "uploads/files"
        
        if not os.path.exists(upload_dir):
            os.makedirs(upload_dir)

        # 生成唯一文件名
        unique_filename = f"{uuid.uuid4()}_{file.filename}"
        file_path = os.path.join(upload_dir, unique_filename)

        # 保存文件
        with open(file_path, "wb") as f:
            f.write(file_data)

    # 保存用户消息到数据库
    user_message = ChatMessage(
        session_id=session_id,
        user_id=current_user.id,  # 使用当前认证用户的ID
        content=message,
        message_type=message_type,
        is_user=True,
        file_path=file_path,
        is_streaming=False,
        is_final=True
    )
    db.add(user_message)

    # 如果是第一条消息，使用AI生成智能会话标题
    if message_count == 0 and session.title == "新会话":
        session.title = await generate_session_title_with_ai(message)

    # 一次性提交所有数据库变更
    db.commit()

    # 创建流式响应
    try:
        # 创建AI消息占位符 - 使用UUID生成消息ID
        message_id = str(uuid.uuid4())

        async def enhanced_stream_generator():
            full_response = ""

            # 获取最近的10条消息（从数据库）构建消息历史
            recent_messages = db.query(ChatMessage).filter(
                ChatMessage.session_id == session_id
            ).order_by(ChatMessage.created_at.desc()).limit(10).all()

            # 按时间顺序排序
            recent_messages.reverse()

            message_history = []
            for msg in recent_messages:
                message_history.append({
                    "role": "user" if msg.is_user else "assistant",
                    "content": msg.content
                })

            # 调用AI模型生成流式响应
            async for chunk in ai_agent.process_message_stream_with_context(
                message_history, message_type, file_data, enable_search
            ):
                full_response += chunk

                # 存储流式数据到Redis
                redis_service.store_streaming_message(
                    session_id=session_id,
                    message_id=message_id,
                    content=full_response,
                    is_final=False
                )

                # 发送SSE格式数据，包含message_id以便前端跟踪
                yield f"data: {json.dumps({'content': chunk, 'session_id': session_id, 'message_id': message_id})}\n\n"

            # 将完成的消息保存到数据库
            ai_message = ChatMessage(
                session_id=session_id,
                user_id=current_user.id,
                content=full_response,
                message_type=message_type,
                is_user=False,
                file_path=None,
                is_streaming=False,
                is_final=True
            )
            db.add(ai_message)
            db.commit()

            # 存储最终状态到Redis
            redis_service.store_streaming_message(
                session_id=session_id,
                message_id=message_id,
                content=full_response,
                is_final=True
            )

            # 发送完成标记，前端可以知道消息已完成
            yield f"data: {json.dumps({'content': '', 'session_id': session_id, 'message_id': message_id, 'is_final': True})}\n\n"

            # 流式输出完成后，删除Redis中的流式数据（保留一段时间供前端恢复）
            # 这里不立即删除，而是让前端在确认接收完成后删除
            # 或者设置较短的过期时间

        # 使用增强的流式生成器
        return StreamingResponse(
            enhanced_stream_generator(),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "X-Session-ID": str(session_id),
                "X-Message-ID": message_id  # 在响应头中包含message_id
            }
        )
    except Exception as e:
        # 错误处理
        error_msg = f"AI服务错误: {str(e)}"
        print(f"处理会话 {session_id} 的消息时出错: {error_msg}")

        # 在错误情况下也存储到Redis
        if message_id:
            redis_service.store_streaming_message(
                session_id=session_id,
                message_id=message_id,
                content=error_msg,
                is_final=True
            )

        # 将错误消息保存到数据库
        ai_message = ChatMessage(
            session_id=session_id,
            user_id=current_user.id,
            content=error_msg,
            message_type=message_type,
            is_user=False,
            file_path=None,
            is_streaming=False,
            is_final=True
        )
        db.add(ai_message)
        db.commit()

        async def error_generator():
            yield f"data: {json.dumps({'error': error_msg, 'session_id': session_id, 'message_id': message_id})}\n\n"

        return StreamingResponse(
            error_generator(),
            media_type="text/event-stream",
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "X-Session-ID": str(session_id)
            }
        )


class StreamingStatusResponse(BaseModel):
    """流式状态响应模型"""
    has_streaming: bool
    message_id: Optional[str] = None
    content: Optional[str] = None
    is_final: Optional[bool] = None


@router.get("/sessions/{session_id}/streaming-status", response_model=StreamingStatusResponse)
async def get_streaming_status(
    session_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """检查会话的流式状态"""
    print(f"[后端日志] 检查会话流式状态 - 会话ID: {session_id}, 用户ID: {current_user.id}")

    # 验证会话属于当前用户
    session = db.query(ChatSession).filter(
        ChatSession.id == session_id,
        ChatSession.user_id == current_user.id
    ).first()

    if not session:
        print(f"[后端日志] 会话不存在 - 会话ID: {session_id}")
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="会话不存在"
        )

    # 检查Redis中是否有活跃的流式会话
    streaming_status = redis_service.get_session_streaming_status(session_id)
    print(f"[后端日志] Redis流式状态查询结果 - 会话ID: {session_id}, 状态: {streaming_status}")

    if streaming_status.get('has_active_streaming', False):
        # 获取第一个活跃消息的数据
        active_messages = streaming_status.get('active_messages', [])
        print(
            f"[后端日志] 发现活跃流式消息 - 会话ID: {session_id}, 活跃消息数: {len(active_messages)}")

        if active_messages:
            message_id = active_messages[0]['message_id']
            streaming_data = redis_service.get_streaming_message(
                session_id, message_id)
            print(
                f"[后端日志] 获取流式数据 - 会话ID: {session_id}, 消息ID: {message_id}, 数据: {streaming_data}")

            if streaming_data:
                print(f"[后端日志] 返回流式状态: 有流式输出 - 会话ID: {session_id}")
                return StreamingStatusResponse(
                    has_streaming=True,
                    message_id=streaming_data.get("message_id"),
                    content=streaming_data.get("content", ""),
                    is_final=streaming_data.get("is_final", False)
                )

    print(f"[后端日志] 返回流式状态: 无流式输出 - 会话ID: {session_id}")
    return StreamingStatusResponse(has_streaming=False)


@router.get("/sessions/{session_id}/streaming-data")
async def get_streaming_data(
    session_id: str,
    message_id: str = Query(..., description="消息ID"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """从Redis获取流式数据（用于前端轮询）"""
    # 验证会话属于当前用户
    session = db.query(ChatSession).filter(
        ChatSession.id == session_id,
        ChatSession.user_id == current_user.id
    ).first()

    if not session:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="会话不存在"
        )

    # 从Redis获取流式数据
    streaming_data = redis_service.get_streaming_message(
        session_id, message_id)

    if streaming_data:
        return {
            "message_id": streaming_data.get("message_id"),
            "content": streaming_data.get("content", ""),
            "is_final": streaming_data.get("is_final", False)
        }
    else:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="没有找到流式数据"
        )


@router.get("/sessions/{session_id}/streaming-data-sse")
async def get_streaming_data_sse(
    session_id: str,
    message_id: str = Query(..., description="消息ID"),
    token: str = Query(None, description="认证令牌（可选）"),
    db: Session = Depends(get_db)
):
    """SSE流式数据接口（用于前端SSE连接）"""

    # 处理认证
    current_user = None
    if token:
        # 尝试通过查询参数验证令牌
        try:
            from auth import get_current_user_from_token
            current_user = get_current_user_from_token(token, db)
        except Exception as e:
            print(f"[后端日志] 令牌验证失败: {str(e)}")

    # 如果没有提供令牌或验证失败，尝试从Authorization头获取
    if not current_user:
        try:
            from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
            security = HTTPBearer()
            credentials: HTTPAuthorizationCredentials = Depends(security)
            from auth import get_current_user
            current_user = get_current_user(credentials, db)
        except Exception as e:
            print(f"[后端日志] Authorization头验证失败: {str(e)}")

    # 如果仍然没有认证用户，检查会话是否属于匿名用户（如果有匿名会话支持）
    if not current_user:
        # 对于SSE连接，我们可以放宽认证要求，只验证会话存在性
        session = db.query(ChatSession).filter(
            ChatSession.id == session_id).first()
        if not session:
            print(f"[后端日志] SSE连接失败 - 会话不存在: {session_id}")
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="会话不存在"
            )
        print(f"[后端日志] SSE连接建立（匿名）- 会话ID: {session_id}, 消息ID: {message_id}")
    else:
        # 验证会话属于当前用户
        session = db.query(ChatSession).filter(
            ChatSession.id == session_id,
            ChatSession.user_id == current_user.id
        ).first()

        if not session:
            print(f"[后端日志] SSE连接失败 - 会话不存在或无权限: {session_id}")
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="会话不存在"
            )
        print(
            f"[后端日志] SSE连接建立 - 会话ID: {session_id}, 消息ID: {message_id}, 用户ID: {current_user.id}")

    async def sse_generator():
        """SSE数据生成器"""
        last_content = ""
        iteration_count = 0

        print(f"[后端日志] SSE生成器启动 - 会话ID: {session_id}, 消息ID: {message_id}")

        while True:
            iteration_count += 1

            # 从Redis获取流式数据
            streaming_data = redis_service.get_streaming_message(
                session_id, message_id)

            if not streaming_data:
                print(
                    f"[后端日志] SSE数据不存在 - 会话ID: {session_id}, 消息ID: {message_id}, 迭代: {iteration_count}")
                # 没有找到流式数据，发送完成信号
                yield f"data: {json.dumps({'error': '流式数据不存在', 'is_final': True})}\n\n"
                break

            current_content = streaming_data.get("content", "")
            is_final = streaming_data.get("is_final", False)

            # 检查是否有新内容
            if current_content != last_content:
                # 只发送新增的内容
                new_content = current_content[len(last_content):]
                if new_content:
                    print(
                        f"[后端日志] SSE发送新内容 - 会话ID: {session_id}, 消息ID: {message_id}, 内容长度: {len(new_content)}, 迭代: {iteration_count}")
                    yield f"data: {json.dumps({'content': new_content, 'message_id': message_id, 'session_id': session_id})}\n\n"
                last_content = current_content
            else:
                print(
                    f"[后端日志] SSE无新内容 - 会话ID: {session_id}, 消息ID: {message_id}, 迭代: {iteration_count}")

            # 如果流式输出已完成，发送完成信号
            if is_final:
                print(
                    f"[后端日志] SSE流式完成 - 会话ID: {session_id}, 消息ID: {message_id}, 迭代: {iteration_count}")
                yield f"data: {json.dumps({'is_final': True, 'message_id': message_id, 'session_id': session_id})}\n\n"
                break

            # 等待一段时间再检查
            await asyncio.sleep(0.1)

    return StreamingResponse(
        sse_generator(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Cache-Control"
        }
    )


@router.delete("/sessions/{session_id}/streaming-data")
async def delete_streaming_data(
    session_id: str,
    message_id: str = Query(..., description="消息ID"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除Redis中的流式数据"""
    # 验证会话属于当前用户
    session = db.query(ChatSession).filter(
        ChatSession.id == session_id,
        ChatSession.user_id == current_user.id
    ).first()

    if not session:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="会话不存在"
        )

    # 删除Redis中的流式数据
    redis_service.delete_streaming_message(session_id, message_id)

    return {"message": "流式数据已删除"}
